import { OnInit, Component, Input, EventEmitter, Output, OnChanges } from '@angular/core';
import { ClassDTO } from 'src/app/project/model/icm/icm-base/class/class.dto';
import { ClassService } from 'src/app/project/service/icm/icm-base/class/class.service';
import { QueryOptions } from 'src/app/project/model/common/query-options';

@Component({
  selector: 'app-class-select',
  templateUrl: './class-select.component.html',
  styles: [],
})
export class ClassSelectComponent implements OnInit, OnChanges {
  constructor(private classService: ClassService) {}

  @Input()
  academyId: string;
  @Input()
  professionId: string;

  @Input()
  classId: string;
  @Output()
  classIdChange = new EventEmitter<string>();

  /**
   * 班级名称
   */
  @Input()
  className: string;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'id,asc',
  };

  /**
   * 是否预览
   */
  @Input()
  isPreView: boolean;

  /**
   * 班级下拉
   */
  classList: Array<ClassDTO> = [];

  /**
   * 班级下拉加载
   */
  isLoading = false;

  /**
   * 获取班级下拉
   */
  getClassDropDownList() {
    this.classList = [];
    this.classService
      .findOnePage(this.queryOptions, null, null, null, this.academyId, this.professionId)
      .subscribe(data => {
        if (data) {
          this.classList.forEach(Class => {
            // 删除与原有班级重复的班级
            data.data.splice(
              data.data.findIndex(item => item === Class),
              1,
            );
          });
          this.classList = [...this.classList, ...data.data];
        }
      });
  }

  /**
   * 弹射数据
   */
  ngModelChange($event: string) {
    this.classIdChange.emit($event);
  }

  ngOnInit() {
    this.getClassDropDownList();
  }

  ngOnChanges() {
    this.getClassDropDownList();
  }
}
